/**
 * 性能监控工具类
 *
 * ========== 性能监控功能详解 ==========
 *
 * 🎯 监控目标：
 * 1. 虚拟化渲染性能：计算耗时、可见节点数量、渲染效率
 * 2. 内存使用情况：DOM节点数量、缓存命中率、内存占用
 * 3. 用户交互性能：缩放平移响应时间、节点点击延迟
 * 4. 帧率监控：FPS统计、掉帧检测、流畅度评估
 *
 * 📊 性能指标：
 * - 渲染效率：可见节点数 / 总节点数
 * - 性能提升：总节点数 / 可见节点数
 * - 内存节省：(总节点数 - 可见节点数) / 总节点数
 * - 缓存命中率：缓存命中次数 / 总访问次数
 *
 * 🔧 优化建议：
 * - 自动检测性能瓶颈并提供优化建议
 * - 实时警告性能异常情况
 * - 生成性能报告和统计图表
 */

/**
 * 性能指标接口
 */
interface PerformanceMetrics {
  /** 时间戳 */
  timestamp: number;
  /** 虚拟化渲染耗时（毫秒） */
  renderTime: number;
  /** 总节点数量 */
  totalNodes: number;
  /** 可见节点数量 */
  visibleNodes: number;
  /** 渲染效率百分比 */
  efficiency: number;
  /** 帧率（FPS） */
  fps: number;
  /** 内存使用量（MB） */
  memoryUsage: number;
}

/**
 * 性能警告级别
 */
export const PerformanceLevel = {
  EXCELLENT: 'excellent' as const,  // 极佳：< 1ms
  GOOD: 'good' as const,           // 良好：1-5ms
  FAIR: 'fair' as const,           // 一般：5-16ms
  POOR: 'poor' as const            // 较差：> 16ms
} as const;

export type PerformanceLevel = typeof PerformanceLevel[keyof typeof PerformanceLevel];

/**
 * 性能监控器类
 */
class PerformanceMonitor {
  // ========== 核心属性 ==========

  /** 性能指标历史记录 */
  private metrics: PerformanceMetrics[] = [];

  /** 最大记录数量 */
  private maxRecords = 100;

  /** FPS计算相关 */
  private frameCount = 0;
  private lastFpsTime = 0;
  private currentFps = 60;

  /** 性能警告回调 */
  private warningCallbacks: ((level: PerformanceLevel, message: string) => void)[] = [];

  // ========== 单例模式 ==========
  private static instance: PerformanceMonitor;

  static getInstance(): PerformanceMonitor {
    if (!PerformanceMonitor.instance) {
      PerformanceMonitor.instance = new PerformanceMonitor();
    }
    return PerformanceMonitor.instance;
  }

  private constructor() {
    // 启动FPS监控
    this.startFpsMonitoring();

    // 启动内存监控
    this.startMemoryMonitoring();
  }

  // ========== 性能记录方法 ==========

  /**
   * 记录虚拟化渲染性能
   *
   * @param renderTime 渲染耗时（毫秒）
   * @param totalNodes 总节点数量
   * @param visibleNodes 可见节点数量
   */
  recordRenderPerformance(renderTime: number, totalNodes: number, visibleNodes: number): void {
    const now = performance.now();
    const efficiency = totalNodes > 0 ? (visibleNodes / totalNodes) * 100 : 0;
    const memoryUsage = this.getMemoryUsage();

    const metrics: PerformanceMetrics = {
      timestamp: now,
      renderTime,
      totalNodes,
      visibleNodes,
      efficiency,
      fps: this.currentFps,
      memoryUsage
    };

    // 添加到历史记录
    this.metrics.push(metrics);

    // 保持记录数量在限制内
    if (this.metrics.length > this.maxRecords) {
      this.metrics.shift();
    }

    // 性能分析和警告
    this.analyzePerformance(metrics);

    // 开发环境日志
    if (import.meta.env.DEV) {
      this.logPerformanceMetrics(metrics);
    }
  }

  /**
   * 获取当前性能统计
   */
  getCurrentStats() {
    if (this.metrics.length === 0) {
      return null;
    }

    const latest = this.metrics[this.metrics.length - 1];
    const avgRenderTime = this.getAverageRenderTime();
    const performanceLevel = this.getPerformanceLevel(latest.renderTime);

    return {
      latest,
      averageRenderTime: avgRenderTime,
      performanceLevel,
      totalRecords: this.metrics.length,
      memoryTrend: this.getMemoryTrend(),
      fpsTrend: this.getFpsTrend()
    };
  }

  /**
   * 获取性能趋势数据
   */
  getPerformanceTrends() {
    if (this.metrics.length < 2) {
      return null;
    }

    const recent = this.metrics.slice(-10); // 最近10条记录

    return {
      renderTimeTrend: recent.map(m => ({ time: m.timestamp, value: m.renderTime })),
      efficiencyTrend: recent.map(m => ({ time: m.timestamp, value: m.efficiency })),
      fpsTrend: recent.map(m => ({ time: m.timestamp, value: m.fps })),
      memoryTrend: recent.map(m => ({ time: m.timestamp, value: m.memoryUsage }))
    };
  }

  // ========== 性能分析方法 ==========

  /**
   * 分析性能指标并发出警告
   */
  private analyzePerformance(metrics: PerformanceMetrics): void {
    const level = this.getPerformanceLevel(metrics.renderTime);

    // 渲染性能警告
    if (level === PerformanceLevel.POOR) {
      this.triggerWarning(level, `渲染性能较差：${metrics.renderTime.toFixed(2)}ms > 16ms，可能影响用户体验`);
    }

    // 效率警告
    if (metrics.efficiency > 50) {
      this.triggerWarning(PerformanceLevel.FAIR, `虚拟化效率较低：${metrics.efficiency.toFixed(1)}%，建议优化节点布局`);
    }

    // FPS警告
    if (metrics.fps < 30) {
      this.triggerWarning(PerformanceLevel.POOR, `帧率过低：${metrics.fps}fps，用户交互可能卡顿`);
    }

    // 内存警告
    if (metrics.memoryUsage > 100) {
      this.triggerWarning(PerformanceLevel.FAIR, `内存使用较高：${metrics.memoryUsage.toFixed(1)}MB，建议清理缓存`);
    }
  }

  /**
   * 获取性能等级
   */
  private getPerformanceLevel(renderTime: number): PerformanceLevel {
    if (renderTime < 1) return PerformanceLevel.EXCELLENT;
    if (renderTime < 5) return PerformanceLevel.GOOD;
    if (renderTime < 16) return PerformanceLevel.FAIR;
    return PerformanceLevel.POOR;
  }

  /**
   * 获取平均渲染时间
   */
  private getAverageRenderTime(): number {
    if (this.metrics.length === 0) return 0;

    const sum = this.metrics.reduce((acc, m) => acc + m.renderTime, 0);
    return sum / this.metrics.length;
  }

  /**
   * 获取内存趋势
   */
  private getMemoryTrend(): 'increasing' | 'decreasing' | 'stable' {
    if (this.metrics.length < 5) return 'stable';

    const recent = this.metrics.slice(-5);
    const first = recent[0].memoryUsage;
    const last = recent[recent.length - 1].memoryUsage;

    const change = ((last - first) / first) * 100;

    if (change > 10) return 'increasing';
    if (change < -10) return 'decreasing';
    return 'stable';
  }

  /**
   * 获取FPS趋势
   */
  private getFpsTrend(): 'increasing' | 'decreasing' | 'stable' {
    if (this.metrics.length < 5) return 'stable';

    const recent = this.metrics.slice(-5);
    const first = recent[0].fps;
    const last = recent[recent.length - 1].fps;

    const change = ((last - first) / first) * 100;

    if (change > 5) return 'increasing';
    if (change < -5) return 'decreasing';
    return 'stable';
  }

  // ========== 监控启动方法 ==========

  /**
   * 启动FPS监控
   */
  private startFpsMonitoring(): void {
    const updateFps = () => {
      this.frameCount++;
      const now = performance.now();

      if (now - this.lastFpsTime >= 1000) { // 每秒更新一次
        this.currentFps = Math.round((this.frameCount * 1000) / (now - this.lastFpsTime));
        this.frameCount = 0;
        this.lastFpsTime = now;
      }

      requestAnimationFrame(updateFps);
    };

    requestAnimationFrame(updateFps);
  }

  /**
   * 启动内存监控
   */
  private startMemoryMonitoring(): void {
    // 每5秒检查一次内存使用情况
    setInterval(() => {
      const memoryUsage = this.getMemoryUsage();

      // 内存使用过高时发出警告
      if (memoryUsage > 200) {
        this.triggerWarning(PerformanceLevel.POOR, `内存使用过高：${memoryUsage.toFixed(1)}MB`);
      }
    }, 5000);
  }

  /**
   * 获取内存使用量
   */
  private getMemoryUsage(): number {
    if ('memory' in performance) {
      // @ts-ignore - performance.memory is not in TypeScript definitions
      return performance.memory.usedJSHeapSize / 1024 / 1024; // 转换为MB
    }
    return 0;
  }

  // ========== 警告系统 ==========

  /**
   * 注册警告回调
   */
  onWarning(callback: (level: PerformanceLevel, message: string) => void): void {
    this.warningCallbacks.push(callback);
  }

  /**
   * 触发警告
   */
  private triggerWarning(level: PerformanceLevel, message: string): void {
    this.warningCallbacks.forEach(callback => {
      try {
        callback(level, message);
      } catch (error) {
        console.error('性能监控警告回调执行失败:', error);
      }
    });
  }

  // ========== 调试和日志 ==========

  /**
   * 记录性能指标到控制台
   */
  private logPerformanceMetrics(metrics: PerformanceMetrics): void {
    const level = this.getPerformanceLevel(metrics.renderTime);
    const levelEmoji = {
      [PerformanceLevel.EXCELLENT]: '🚀',
      [PerformanceLevel.GOOD]: '⚡',
      [PerformanceLevel.FAIR]: '✅',
      [PerformanceLevel.POOR]: '⚠️'
    };

    console.log(`${levelEmoji[level]} 性能监控:`, {
      '渲染耗时': `${metrics.renderTime.toFixed(2)}ms`,
      '节点效率': `${metrics.visibleNodes}/${metrics.totalNodes} (${metrics.efficiency.toFixed(1)}%)`,
      '帧率': `${metrics.fps}fps`,
      '内存': `${metrics.memoryUsage.toFixed(1)}MB`,
      '性能等级': level
    });
  }

  /**
   * 生成性能报告
   */
  generateReport(): string {
    const stats = this.getCurrentStats();
    if (!stats) {
      return '暂无性能数据';
    }

    return `
📊 虚拟化渲染性能报告
====================

🎯 当前状态:
- 渲染耗时: ${stats.latest.renderTime.toFixed(2)}ms
- 渲染效率: ${stats.latest.efficiency.toFixed(1)}%
- 帧率: ${stats.latest.fps}fps
- 内存使用: ${stats.latest.memoryUsage.toFixed(1)}MB
- 性能等级: ${stats.performanceLevel}

📈 性能趋势:
- 内存趋势: ${stats.memoryTrend}
- 帧率趋势: ${stats.fpsTrend}
- 平均渲染时间: ${stats.averageRenderTime.toFixed(2)}ms
- 总记录数: ${stats.totalRecords}

💡 优化建议:
${this.generateOptimizationSuggestions(stats)}
    `.trim();
  }

  /**
   * 生成优化建议
   */
  private generateOptimizationSuggestions(stats: any): string {
    const suggestions: string[] = [];

    if (stats.latest.renderTime > 16) {
      suggestions.push('- 考虑使用四叉树空间索引加速碰撞检测');
    }

    if (stats.latest.efficiency > 50) {
      suggestions.push('- 增加缓冲区大小或优化节点布局密度');
    }

    if (stats.latest.fps < 30) {
      suggestions.push('- 减少DOM操作频率，使用requestAnimationFrame优化动画');
    }

    if (stats.memoryTrend === 'increasing') {
      suggestions.push('- 检查内存泄漏，清理不必要的缓存');
    }

    return suggestions.length > 0 ? suggestions.join('\n') : '- 当前性能表现良好，无需优化';
  }

  // ========== 清理方法 ==========

  /**
   * 清理性能数据
   */
  clear(): void {
    this.metrics = [];
    this.frameCount = 0;
    this.lastFpsTime = 0;
    this.currentFps = 60;
  }

  /**
   * 导出性能数据
   */
  exportData(): PerformanceMetrics[] {
    return [...this.metrics];
  }
}

// 导出单例实例
export const performanceMonitor = PerformanceMonitor.getInstance();
export type { PerformanceMetrics };
